<template>
  <div>
    <el-row style="align-items: center;" :gutter="24">
      <el-col :span="1"></el-col>
      <el-col :span="4" style="display: flex; align-items: center; height: 100%;">
        <div style="width: 100%; display: flex; align-items: center; height: 100%; margin-top: 20px;">
          <Breadcrumb />
        </div>
      </el-col>
      <el-col :span="13"></el-col>
      <el-col :span="2" style="display: flex; align-items: center; justify-content: flex-end;">
        <!-- 锁屏组件及按钮在左侧 -->
        <div style="display: flex; align-items: center; margin-top: -32px;">
          <!-- 刷新卡片按钮（添加 Refresh 图标） -->
          <el-button
            class="refresh-card-btn"
            style="margin-right: 16px; background: #fff; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); border: 1px solid #e6e6e6; padding: 8px; display: flex; align-items: center; justify-content: center;"
            type="default"
            circle
            @click="refreshPage"
          >
            <el-icon><Refresh /></el-icon>
          </el-button>
          <lockScreen 
            v-model="isLocked" 
            :timer="300"
            :width="`100vw`"
            :height="`100vh`"
            @enter="handleUnlock"
          />
          <!-- 锁屏按钮（添加 Lock 图标） -->
          <el-button size="small" style="margin-right: 12px; display: flex; align-items: center;" @click="isLocked = true">
            <el-icon style="margin-right: 4px;"><Lock /></el-icon>
            锁屏
          </el-button>
          <el-button
            class="chat-card-btn"
            @click="openDialog"
            style="margin-right: 32px;"
            type="default"
            circle
          >
            <el-icon><ChatRound /></el-icon>
          </el-button>
        </div>
      </el-col>
      <el-col :span="0"></el-col>
      <el-col :span="3" style="display: flex; justify-content: flex-end; align-items: center; margin-top: -32px;">
        <el-dropdown @command="handleDropdownCommand" trigger="click" :hide-on-click="false">
          <template #default>
            <el-icon style="font-size: 28px;"><User /></el-icon>
            <span style="color: azure">您好！{{ userName }}</span>
          </template>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="openPersonalSpace">个人空间</el-dropdown-item>
              <el-dropdown-item @click="openPersonalEdit">个人修改</el-dropdown-item>
              <el-dropdown-item>
                <el-popconfirm
                  confirm-button-text="是的"
                  cancel-button-text="不用了"
                  icon="el-icon-info"
                  icon-color="red"
                  title="您确认要注销吗？"
                  @confirm="logOut"
                >
                  <template #reference>
                    <el-button type="text">注销</el-button>
                  </template>
                </el-popconfirm>
              </el-dropdown-item>
              <el-dropdown-item>
                <div @click.stop style="display: flex; align-items: center;">
                  <el-color-picker
                    v-model="color"
                    show-alpha
                    :predefine="predefineColors"
                    @active-change="handleColorChange"
                  />
                </div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-col>
    </el-row>
    
    <!-- 个人修改抽屉 -->
    <el-drawer
      title="个人信息修改"
      :before-close="handleCloseEdit"
      v-model:visible="editDialog"
      direction="rtl"
      custom-class="demo-drawer"
      ref="editDrawer"
    >
      <el-form :model="form">
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input v-model="user[0].name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="职业" :label-width="formLabelWidth">
          <el-select v-model="user[0].position" placeholder="请选择分类" style="width: 100%;">
            <el-option label="管理员" value="管理员" />
            <el-option label="保安" value="保安" />
            <el-option label="保洁" value="保洁" />
          </el-select>
        </el-form-item>
        <el-form-item label="电话号码" :label-width="formLabelWidth">
          <el-input v-model="user[0].phoneNumber" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div class="demo-drawer__footer">
        <el-button @click="cancelForm">取 消</el-button>
        <el-button type="primary" @click="updateSubmit">确 定</el-button>
      </div>
    </el-drawer>
    
    <!-- 个人空间抽屉 -->
    <el-drawer
      title="个人空间"
      :before-close="handleCloseSpace"
      v-model:visible="spaceDialog"
      direction="rtl"
      custom-class="demo-drawer"
      ref="spaceDrawer"
    >
      <div>
        <h3>个人资料</h3>
        <el-descriptions column="1" border>
          <el-descriptions-item label="姓名">{{ user[0]?.name || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="账号">{{ user[0]?.account || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="职业">{{ user[0]?.position || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="电话号码">{{ user[0]?.phoneNumber || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="入职日期">{{ user[0]?.hireDate || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="员工ID">{{ user[0]?.employeeId || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ user[0]?.status || '未设置' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <div class="demo-drawer__footer">
        <el-button @click="spaceDialog = false">关 闭</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<style scoped>
.chat-card-btn {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  border: 1px solid #e6e6e6;
  padding: 8px;
  transition: box-shadow 0.2s, border-color 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}
.chat-card-btn:hover {
  box-shadow: 0 4px 16px rgba(31,147,255,0.18);
  border-color: #409eff;
}
.chat-card-btn .el-icon {
  font-size: 22px;
  color: #409eff;
}
.refresh-card-btn:hover {
  box-shadow: 0 4px 16px rgba(31,147,255,0.18);
  border-color: #409eff;
}
.refresh-card-btn .el-icon {
  font-size: 22px;
  color: #409eff;
}
</style>

<script setup>
// 对话按钮点击事件
const refreshPage = () => {
  window.location.reload();
};
const openDialog = () => {
  router.push('/chat');
};
import { ref, reactive, onBeforeMount } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElButton, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElDrawer, ElRow, ElCol, ElDropdown, ElDropdownMenu, ElDropdownItem, ElColorPicker, ElPopconfirm, ElDescriptions, ElDescriptionsItem } from 'element-plus';
// 导入需要的图标（新增 Refresh、Lock）
import { User, ChatRound, Refresh, Lock } from '@element-plus/icons-vue';
import Breadcrumb from './Breadcrumb.vue';
import { post } from '../../utils/axios.js';
import { lockScreen } from '../../utils/index.js';
const router = useRouter();

const color = ref(localStorage.getItem('headerColor') || 'rgba(31, 147, 255, 0.73)');
const predefineColors = [
  '#ff4500', '#ff8c00', '#ffd700', '#90ee90',
  '#00ced1', '#1e90ff', '#c71585', 'rgba(255, 69, 0, 0.68)',
  'rgb(255, 120, 0)', 'hsv(51, 100, 98)', 'hsva(120, 40, 94, 0.5)',
  'hsl(181, 100%, 37%)', 'hsla(209, 100%, 56%, 0.73)', '#c7158577',
];
const userName = ref(window.sessionStorage.getItem('account'));
const user = ref([]);
const editDialog = ref(false);  // 个人修改对话框
const spaceDialog = ref(false); // 个人空间对话框
const formLabelWidth = '80px';
const loading = ref(false);
const timer = ref(null);
const handleDropdownCommand = (cmd) => {
  if (cmd === 'space') spaceDialog.value = true;
  if (cmd === 'edit') editDialog.value = true;
};
const handleColorChange = (newColor) => {
  color.value = newColor;
  localStorage.setItem('headerColor', newColor);
  // 通知父组件同步顶部栏颜色
  if (typeof window !== 'undefined') {
    const event = new CustomEvent('updateHeaderColor', { detail: newColor });
    window.dispatchEvent(event);
  }
};
const isLocked = ref(false);

// 处理解锁逻辑
const handleUnlock = (password) => {
  if (password === 'rfy') {
    isLocked.value = false;
  } else {
    alert('密码错误，请重试');
  }
};

const logOut = () => {
  window.sessionStorage.setItem('loginState', false);
  router.push('/login');
};

// 打开个人空间
const openPersonalSpace = () => {
  spaceDialog.value = true;
  console.log('个人空间已打开');
};

// 打开个人修改
const openPersonalEdit = () => {
  editDialog.value = true;
};

// 关闭个人修改抽屉
const handleCloseEdit = (done) => {
  if (loading.value) {
    return;
  }
  ElMessage.confirm('确定要关闭吗？未保存的内容将丢失')
    .then(() => {
      done();
    })
    .catch(() => {});
};

// 关闭个人空间抽屉
const handleCloseSpace = (done) => {
  done();
};

const cancelForm = () => {
  loading.value = false;
  editDialog.value = false;
  clearTimeout(timer.value);
};

const updateSubmit = () => {
  if (!user.value || user.value.length === 0) {
    ElMessage.error('未获取到用户信息');
    return;
  }
  
  const form = {
    name: user.value[0].name,
    position: user.value[0].position,
    status: user.value[0].status,
    account: user.value[0].account,
    phoneNumber: user.value[0].phoneNumber,
    hireDate: user.value[0].hireDate,
    employeeId: user.value[0].employeeId,
  };
  
  loading.value = true;
  post('/sc/api/staff/update_info', form, (res) => {
    loading.value = false;
    if (res.status === 1) {
      ElMessage.success('修改成功！');
      editDialog.value = false;
    } else {
      ElMessage.error('修改失败：' + (res.msg || '未知错误'));
    }
  }, (error) => {
    loading.value = false;
    ElMessage.error('请求失败：' + error.message);
  });
};

onBeforeMount(() => {
  // 页面加载时自动同步顶部栏颜色
  if (typeof window !== 'undefined') {
    window.addEventListener('updateHeaderColor', (e) => {
      if (e.detail && document.querySelector('.el-header')) {
        document.querySelector('.el-header').style.backgroundColor = e.detail;
      }
    });
    // 首次加载时同步
    if (document.querySelector('.el-header')) {
      document.querySelector('.el-header').style.backgroundColor = color.value;
    }
  }
  const data = {
    account: window.sessionStorage.getItem('account'),
    name: null,
    position: null,
    status: null,
  };
  
  post('/sc/employee/getByCondition', data, (res) => {
    if (res.status === 1) {
      user.value = res.data;
      // 如果有用户名，更新显示
      if (user.value && user.value.length > 0 && user.value[0].name) {
        userName.value = user.value[0].name;
      }
    } else {
      ElMessage.error('未查询到数据，请重新查询');
    }
  });
});
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #cf40ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-drawer__body {
  overflow-y: scroll;
  margin-bottom: 50px;
  padding: 20px;
}

.demo-drawer__footer {
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: center;
  background-color: white;
}

h3 {
  margin-bottom: 20px;
  color: #333;
}
</style>